package com.ylbh.common.utils;

import com.baidu.aip.imagesearch.AipImageSearch;
import com.ylbh.common.pojo.goods.dto.GoodsDTO;
import com.ylbh.common.pojo.goods.vo.GoodsDetailsVO;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;

/**
 * 百度云图片检索
 * @author mgh
 */
@Component
public class PictureRetrievalUtils {
    @Value("${imgsearch.songbei.appId}")
    public String searchAppId;

    @Value("${imgsearch.songbei.apiKey}")
    public String searchApiKey;

    @Value("${imgsearch.songbei.secretKey}")
    public String searchSecretKey;

    private Logger logger = LoggerFactory.getLogger(PictureRetrievalUtils.class);

    private AipImageSearch init(){
        AipImageSearch client = new AipImageSearch(searchAppId, searchApiKey, searchSecretKey);
        client.setConnectionTimeoutInMillis(2000);
        client.setSocketTimeoutInMillis(60000);
        return client;
    }

    /**
     * 商品检索—入库
     * 注：重复添加完全相同的图片会返回错误。
     */
    public synchronized void productAddUrl(GoodsDTO goodsQueryVO) {
        AipImageSearch client = init();
        HashMap<String, String> options = null;
        // 传入可选参数调用接口
        options = new HashMap<String, String>();
        options.put("brief", "{\"id\":\""+goodsQueryVO.getId()+"\"}");
        // 商品所属分类
        options.put("class_id1", goodsQueryVO.getGcId()== null ?"1":goodsQueryVO.getGcId().toString());
        // 商品所属兑换还是福利
        options.put("class_id2", goodsQueryVO.getPriceType().toString());
        // 商品检索—入库, 图片参数为远程url图片
        String res = client.productAddUrl(goodsQueryVO.getMainImgUrl(), options).toString(2);
        logger.info("图片检索----添加图片返回值{}",res);
    }

    /**
     * 商品检索—删除
     */
    public void productDeleteByUrl(GoodsDetailsVO goodsDetailsVO) {
        AipImageSearch client = init();
        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<String, String>();
        // 商品所属分类
        options.put("class_id1", goodsDetailsVO.getGcId()== null ?"1":goodsDetailsVO.getGcId().toString());
        // 商品所属兑换还是福利 商品类型 0:纯现金 1:兑换商品 2:福利商品
        options.put("class_id2", goodsDetailsVO.getPriceType().toString());

        // 删除商品，图片参数为远程url图片
        JSONObject res = client.productDeleteByUrl(goodsDetailsVO.getImg(), options);
        logger.info("图片检索----删除图片返回值{}",res);
    }
}
